import React, {FC, forwardRef, useEffect, useImperativeHandle, useRef, useState} from 'react'
import './index.css'
import {
    Button,
    Form,
    Input,
    Select,
    Table,
    Tag,
    Drawer,
    message,
    TimePicker,
    DatePicker,
    Cascader,
    TreeSelect, Modal
} from "antd";
import {
    CloseOutlined, DeleteOutlined,
    EditOutlined,
    ExclamationCircleOutlined, EyeOutlined,
    PlusOutlined,
    SearchOutlined,
    SyncOutlined
} from "@ant-design/icons";
// @ts-ignore
import shortid from 'shortid'
import {fetchRequest} from "@/utils/Request";
import {url} from "@/utils/url";
import moment, {Moment} from "moment/moment";
import {useRequest} from "@umijs/hooks";
import {useHistory} from "react-router";
import TableToolbar from "@/components/TableSetting/TableToolbar";

const {Option} = Select
const {RangePicker} = TimePicker;
const {RangePicker: DateRangePicker} = DatePicker;
const {confirm} = Modal;
const timerList = [
    {
        title: '星期一',
        value: '1'
    },
    {
        title: '星期二',
        value: '2'
    },
    {
        title: '星期三',
        value: '3'
    },
    {
        title: '星期四',
        value: '4'
    },
    {
        title: '星期五',
        value: '5'
    },
    {
        title: '星期六',
        value: '6'
    },
    {
        title: '星期天',
        value: '7'
    }]


const {SHOW_PARENT} = TreeSelect;

const Curriculum: FC = () => {

    const [visible, setVisible] = useState(false)
    const [id, setId] = useState<any>('')
    const aTable = useRef<any>(null)
    const aDrawer = useRef<any>(null)

    const edit = (id: string) => {
        setId(id)
        setVisible(true)
    }


    const [params, setParams] = useState<any>({})
    const onAdd = () => {
        setId('')
        setVisible(true)
        aDrawer.current.clear()
    }

    return (<div className={'wrap'}>
        <Search setVisible={() => {
            setVisible(true);
            setId('')
        }}
                setParams={setParams}
                visible={visible}
        />
        <ATable edit={edit} params={params} setVisible={setVisible} ref={aTable} onAdd={onAdd}/>
        <ADrawer visible={visible} id={id} setVisible={setVisible} ref={aDrawer}
                 refresh={() => aTable.current.refresh()}/>
    </div>)
}

const Search: FC<{ setParams: (params: any) => void, setVisible: (visible: boolean) => void, visible: boolean }> = ({
                                                                                                                        setVisible,
                                                                                                                        setParams,
                                                                                                                        visible
                                                                                                                    }) => {

    const [form] = Form.useForm();
    const [ruleList, setRuleList] = useState([])
    const [treeNode, setTreeNode] = useState<any>([]);
    const [classValue, setClassValue] = useState<any>([])
    /*添加api*/
    const {run} = useRequest(() => fetchRequest(url.GET_STATE_LIST, {}), {
        manual: true,
        onSuccess: async (result, params) => {


            if (result.success) {

                setRuleList(result.data)


            } else {
                message.error(result.errorMsg)
            }
        }
    })

    useEffect(() => {
        run()
    }, [])


    const onReset = () => {
        form.resetFields();
        setParams({})
        getSchoolOrganizationRequest(requestParamTree)
    };

    const onFinish = (values: any) => {
        console.log(values)

        setParams({
            ...values,
            deptId:values?.deptId?.value
        })

    }

    const loadData = async ({treeId, level}: any) => {

        await getSchoolOrganizationRequest({treeId, level: level + 1})

    };

    //请求在校学生组织机构
    async function getSchoolOrganizationRequest(params: any) {
        try {
            const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);

            console.log(json)
            if (json.success) {
                message.destroy();
                const list = json.data.map((item: any) => {
                    let temp
                    delete item.children;

                    temp = {...item, pId: item.parentId, id: item.treeId}
                    return temp
                });


                if (params.level === 0) {
                    setTreeNode(list);
                } else {
                    setTreeNode((data: any) => {
                        console.log(data)
                        return [...data, ...list]
                    })
                }


            } else {
                message.destroy();
                message.error(json.errorMsg)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)

        }

    }

    const [requestParamTree] = useState<any>(
        {
            "level": 0,
            "treeId": "0"
        }
    );

    useEffect(() => {
        getSchoolOrganizationRequest(requestParamTree)
    }, [requestParamTree, visible])

    const onChange = (value: any) => {
     
        setClassValue(value)


    }

    const tProps = {
        treeData: treeNode,
        value: classValue,
        labelInValue:true,
        loadData,
        onChange,
        treeDataSimpleMode: true,
        showCheckedStrategy: SHOW_PARENT,
        placeholder: '请选择班级范围',
        style: {
            width: '100%',
        },
    }




    return <div className={'curriculum-search'}>
        <Form form={form} layout={'inline'} onFinish={onFinish}>
            <Form.Item label="标题" name={'ruleName'}>
                <Input placeholder="请输入标题"/>
            </Form.Item>
            <Form.Item label="状态" name={'state'}>
                <Select style={{width: 300}} placeholder={'请选择状态'}>
                    {ruleList.map((item: any) => <Option key={item.state_id}
                                                         value={item.state_id}>{item.state_name}</Option>)}
                </Select>
            </Form.Item>

            <Form.Item label="组织机构" name={'deptId'} style={{width: 300}}>

                <TreeSelect  {...tProps} placeholder={'请选择组织机构'}/>
            </Form.Item>
            <Form.Item>
                <Button key="1" type="primary" icon={<SearchOutlined/>} htmlType="submit"
                        style={{marginRight: '8px'}}>搜索</Button>
                <Button key="2" icon={<SyncOutlined/>} onClick={onReset}>重置</Button>

            </Form.Item>
        </Form>
    </div>
}


const ATable = forwardRef<any, { edit: (id: string) => void, params: any, setVisible: (visible: boolean) => void, onAdd: () => void }>(({
                                                                                                                                            edit,
                                                                                                                                            params,
                                                                                                                                            setVisible,
                                                                                                                                            onAdd
                                                                                                                                        }, ref) => {


    const {
        tableProps,
        run,
        refresh
    } = useRequest(((current, params) => fetchRequest(url.SELECT_RULE_TABLE, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params

    })), {
        paginated: true,
        manual: true,
        formatResult: (response: any) => {
            return {
                list: response.data?.rows,
                total: response.data?.total,
                success: response.success,
                errorMsg: response.errorMsg
            };
        }
    })

    useImperativeHandle(ref, () => ({
        refresh
    }))


    useEffect(() => {
        console.log(params);
        
        run({pageSize: 10, current: 1}, {...params})
    }, [params.ruleName, params.state, params.deptId])


    //删除
    const {run: deletedRun} = useRequest((params) => fetchRequest(url.DELETE_RULE_ID, params), {
        manual: true,
        onSuccess: async (result, params: any) => {
            if (result.success) {

                message.success(result.data)
            } else {

                message.error(result.errorMsg)
            }
        }

    })


    //启动或者关闭
    const {run: openRun} = useRequest((params) => fetchRequest(url.OPEN_RULE_STATE, params), {
        manual: true,
        onSuccess: async (result, params: any) => {
            if (result.success) {

                message.success(result.data)
            } else {

                message.error(result.errorMsg)
            }
        }

    })


    const router = useHistory()


    const columns = [
        {
            title: '标题',
            dataIndex: 'ruleName',
            key: 'ruleName',
        },
        {
            title: '适用范围',
            dataIndex: 'deptName',
            key: 'deptName',
        }, {
            title: '状态',
            key: '状态',

            render: (item: any) => {
                return <><Tag color={item.color}>{item.stateName}</Tag></>
            }
        }, {
            title: '操作',
            key: '操作',
            render: (item: any) => {

                const title = `${item.state == '2' || item.state == '5' || item.state == '4' ? '启用' : '停用'}`
                const flag = item.state == '2' || item.state == '5' || item.state == '4' ? 1 : 0

                const color = flag ? '#8fd224' : '#ff0000'


                let list = [
                    {
                        title: '查看',
                        color: '#0053ff',
                        icon: <EyeOutlined/>,
                        onClick: () => {
                            router.push(`/homepage/entranceManage/curriculumStudent/${item.ruleId}`)

                        }
                    },
                    {
                        title: '编辑',
                        color: '#0053ff',
                        icon: <EditOutlined/>,
                        onClick: () => {
                            edit(item.ruleId)
                        }
                    },
                    {
                        title: '删除',
                        color: '#ff0505',
                        icon: <DeleteOutlined/>,

                        onClick: async () => {

                            confirm({
                                title: '删除',
                                icon: <ExclamationCircleOutlined/>,
                                content: '确认删除该规则吗?',
                                okText: '确定',
                                okType: 'danger',
                                cancelText: '取消',
                                async onOk() {
                                    await deletedRun({ruleId: item.ruleId, state: item.state})
                                    await refresh()
                                },
                            });
                        }
                    },
                ]
                if (item.state != 6 && item.state != 7 && item.state != 3) {
                    list = [{
                        title: title,
                        color: color,
                        icon: <EditOutlined/>,
                        onClick: () => {

                            confirm({
                                title: '提示',
                                icon: <ExclamationCircleOutlined/>,
                                content: `是否${title}该条规则？`,
                                okText: '确定',
                                okType: 'danger',
                                cancelText: '取消',
                                async onOk() {
                                    await openRun({ruleId: item.ruleId, flag, state: item.state})

                                    await refresh()
                                },
                            });


                        }
                    }, ...list]

                }


                return <>
                    {list.map(item => <Tag key={item.title}  {...item}>{item.title}</Tag>)}
                </>
            }
        }
    ]

    const [columnsKey, setcolumnsKey] = useState<any[]>([])
    const [realColumns, setrealColumns] = useState<any[]>([])
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        console.log(realColumns,11);
        
        setrealColumns(realColumns)
    }, [columnsKey])

   
    

    return <>
        <div className={'curriculum-table-wrap'}>
            <TableToolbar tableName={'智能学生证免打扰列表'} columns={columns} onColumnsChange={(checkedList:any) => {
             setcolumnsKey(checkedList)
            
            }}
                          onRefresh={() => refresh()} onAdd={onAdd}
            />
            <Table {...tableProps as any} rowKey={'ruleId'} columns={realColumns}/>
        </div>
    </>
})

const ADrawer = forwardRef<any, { visible: boolean, setVisible: (visible: boolean) => void, id: string, refresh: () => void }>(({
                                                                                                                                    visible,
                                                                                                                                    setVisible,
                                                                                                                                    id,
                                                                                                                                    refresh
                                                                                                                                }, ref) => {


    const [form] = Form.useForm();


    const [treeNode, setTreeNode] = useState<any>([]);
    const [classValue, setClassValue] = useState([]);

    useImperativeHandle(ref, () => ({
        clear: () => {
            form.resetFields()
        }
    }))


    const [requestParamTree] = useState<any>(
        {
            "level": 0,
            "treeId": "0"
        }
    );


    /*添加api*/
    const {run} = useRequest((params) => fetchRequest(url.ADD_STUDENT_RULE, params), {
        manual: true,
        onSuccess: async (result, params) => {
            if (result.success) {
                setVisible(false)

                message.success(result.data)

            } else {
                message.error(result.errorMsg)
            }
        }
    })

    /*查询api*/
    const {run: selectRun} = useRequest((params) => fetchRequest(url.SELECT_RULE_INFO, params), {
        manual: true,
        onSuccess: async (result, params) => {
            if (result.success) {

                result?.data?.wisdomRuleList?.map((item: any) => {
                    item.normalTimes = item.normalTimes.split('-')
                    item.weekDay = item.weekDay.split(',')
                    return item
                })

                console.log(result.data)

                form.setFieldsValue({
                    ...result?.data
                })


            } else {
                message.error(result.errorMsg)
            }
        }
    })


    const loadData = async ({treeId, level}: any) => {

        await getSchoolOrganizationRequest({treeId, level: level + 1})

    };

    //请求在校学生组织机构
    async function getSchoolOrganizationRequest(params: any) {
        try {
            const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);


            if (json.success) {
                message.destroy();
                const list = json.data.map((item: any) => {
                    let temp
                    delete item.children;
                    temp = {...item, pId: item.parentId, id: item.treeId}
                    return temp
                });


                if (params.level === 0) {
                    setTreeNode(list);
                } else {
                    setTreeNode((data: any) => {
                        return [...data, ...list]
                    })
                }


            } else {
                message.destroy();
                message.error(json.errorMsg)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)

        }

    }


    useEffect(() => {
        getSchoolOrganizationRequest(requestParamTree)
    }, [requestParamTree])


    useEffect(() => {

        if (id) {

            selectRun({ruleId: id})
        } else {
            form.resetFields();
        }
    }, [id])


    const onChange = (value: any) => {
        setClassValue(value)

    }
    const tProps = {
        treeData: treeNode,
        loadData,
        onChange,
        treeDataSimpleMode: true,
        treeCheckable: true,
        showCheckedStrategy: SHOW_PARENT,
        placeholder: '请选择班级范围',
        labelInValue: true,
        style: {
            width: '100%',
        },
    }
   
    const formLayout = {
        labelCol: {span: 2},
        wrapperCol: {span: 10},
    }

    const onFinish = async (values: any) => {

        const params = JSON.parse(JSON.stringify(values));

        console.log(params)
        params.ruleList = params.wisdomRuleList?.map((item: any) => {
                item.normalTimes = item.normalTimes.join('-')

                item.weekDay = item.weekDay.join(',')
                return item
            }
        )

        params.deptId = params.dept?.map((item: any) => item.value)


        params.ruleId = id ?? undefined
        console.log(params.deptId)

        await run({
            ...params,
        })
        await refresh()


    }


    //获取班级范围
    return (<>

        <Drawer title="信息" placement="right" width={1200} visible={visible} onClose={() => {
            setVisible(false);


        }}
                destroyOnClose getContainer={false}>
            <Form form={form}      {...formLayout}
                  onFinish={onFinish}

                  initialValues={{
                      ruleName: '',
                      deptId: [],
                      wisdomRuleList: [{weekDay: [], name: '', normalTimes: [], seq: shortid.generate()}]
                  }}
            >
                <Form.Item label="标题" name={'ruleName'} rules={[{required: true, message: '请输入标题'}]}>
                    <Input placeholder='请输入标题'/>
                </Form.Item>
                <Form.Item label="班级范围" name={'dept'} rules={[{required: true, message: '请选择班级范围'}]}>

                    <TreeSelect  {...tProps}/>

                </Form.Item>
                <Form.Item label="规则" name="wisdomRuleList" labelCol={{span: 2}} wrapperCol={{span: 22}}>
                    <AccessBox/>
                </Form.Item>
                <Form.Item className={'access-box-bt-btn'} labelCol={{}} wrapperCol={{span: 24}}>
                    <Button type={'primary'} htmlType="submit">提交</Button>
                </Form.Item>

            </Form>
        </Drawer>
    </>)
})


const AccessBox: FC<{ value?: any, onChange?: (state: any) => void }> = ({value, onChange}) => {
    //一般规则门禁盒子


    const [showBtn, setShowBtn] = useState(true)

    const triggerChange = (changedValue: any) => {

        onChange?.([...changedValue]);

    };

    //点击添加门禁盒子
    const addAccess = () => {


        if (value) {
            triggerChange([...value, {weekDay: [], name: '', normalTimes: [], seq: shortid.generate()}])
        } else {
            triggerChange([{weekDay: [], name: '', normalTimes: [], seq: shortid.generate()}])
        }

    }

    //删除门禁盒子
    const deleteAccess = (item: any) => {
        triggerChange(value?.filter((access: any) => access?.seq !== item?.seq))
    }

    //选择门禁盒子
    const changeAccess = (timer: any, timeString: any, item: any) => {
        triggerChange(value?.map((access: any) => {
                if (access.seq === item.seq) {
                    access.normalTimes = timeString
                }
                return access
            })
        )

    }

    const changeName = (e: any, item: any) => {

        const {value: values} = e.target;
        triggerChange(value?.map((access: any) => {
            if (access.seq === item.seq) {
                access.name = values
            }
            return access
        }))
    }

    const changeTimes = (values: any, item: any) => {


        triggerChange(value?.map((access: any) => {
                if (access.seq === item.seq) {
                    access.weekDay = values
                }
                return access
            })
        )
    }


    useEffect(() => {
        setShowBtn(value?.length !== 5)
    }, [value])


    return (<>
        {value?.map((item: any, i: number) => <div key={item.seq} className={'access-box-item flex'}>
            <div className={'flex access-box-item-item'}>
                <div className={'access-box-title'}>标题：</div>
                <div>
                    <Input placeholder={'请输入标题'} value={item.name} onChange={(e) => changeName(e, item)}/>
                </div>
            </div>
            <div className={'flex access-box-item-item'}>
                <div className={'access-box-title'}>周期：</div>
                <Select style={{width: '300px'}} mode="multiple" maxTagCount={3} placeholder={'请选择周期'}
                        value={item.weekDay}
                        onChange={(value) => changeTimes(value, item)}>
                    {timerList.map(item => <Option key={item.value} value={item.value}>{item.title}</Option>)}
                </Select>
            </div>
            <div className={'flex access-box-item-item'}>
                <div className={'access-box-title'}>时间：</div>
                <div>
                    <RangePicker allowClear format="HH:mm"
                                 defaultValue={item?.normalTimes?.map((item: any) => moment(item, 'HH:mm'))}
                                 onChange={(timer, timeString) => changeAccess(timer, timeString, item)}/>

                </div>
                <div className={'access-box-btn'}>
                    {i != 0 ? <Button type={'primary'} icon={<CloseOutlined/>} danger
                                      onClick={() => deleteAccess(item)}>删除</Button> : null}

                </div>
            </div>
        </div>)}
        {showBtn ?
            <div className={'access-box-add'}>
                <Button type={'primary'} icon={<PlusOutlined/>}
                        onClick={addAccess}>添加</Button>
            </div>
            : null}


    </>)
}


export default Curriculum
